import { useEffect } from "react";
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import { forwardRef, useImperativeHandle } from "react";
import * as z from "zod";
import { zodResolver } from "@hookform/resolvers/zod";
import { useForm } from "react-hook-form";
import { CreateCookieSchema } from "@/schemas";
import { IPlatform, IFormRef } from "../../types";

interface FormProps {
  handleSubmit: (values: z.infer<typeof CreateCookieSchema>) => void;
  platform: IPlatform | null;
}

const CookiesForm = forwardRef<IFormRef, FormProps>(
  ({ handleSubmit, platform }, ref) => {
    const form = useForm<z.infer<typeof CreateCookieSchema>>({
      resolver: zodResolver(CreateCookieSchema),
      defaultValues: {
        name: "tb",
        platformId: platform?.id || 0,
      },
    });
    useEffect(() => {
      form.setValue("platformId", platform?.id || 0);
    }, [platform, form]);

    useImperativeHandle(ref, () => ({
      onSubmit: async () => {
        try {
          const isValid = await form.trigger();
          if (isValid) {
            const values = form.getValues();
            handleSubmit(values);
          } else {
            console.log("Validation failed");
          }
        } catch (error) {
          console.error("Error during form submission:", error);
        }
      },
    }));

    return (
      <Form {...form}>
        <form className="space-y-4">
          <FormField
            control={form.control}
            name="name"
            render={({ field }) => (
              <FormItem className="flex flex-row items-center py-4 text gap-4">
                <FormLabel htmlFor="id_name" className="w-20">
                  名称
                </FormLabel>
                <FormControl>
                  <Input id="id_name" {...field} className="w-60" />
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />
          <FormField
            control={form.control}
            name="platformId"
            render={({ field }) => {
              return (
                <FormItem className="flex flex-row items-center py-4 gap-4">
                  <FormLabel htmlFor="id_name" className="w-20">
                    平台
                  </FormLabel>
                  <FormControl>
                    <div>
                      <div className="group">
                        <div className="group-hover:hidden">
                          <Input
                            readOnly
                            id="id"
                            value={platform?.name || "未定义"}
                            className="w-60"
                          />
                        </div>
                        <div className="hidden group-hover:flex">
                          <Input
                            id="id_name"
                            className="w-60"
                            type="number"
                            readOnly
                            {...field}
                          />
                        </div>
                      </div>
                    </div>
                  </FormControl>

                  <FormMessage />
                </FormItem>
              );
            }}
          />

          <FormField
            control={form.control}
            name="file"
            render={({ field }) => (
              <FormItem className="flex flex-row items-center py-4 gap4">
                <FormLabel className="w-20" htmlFor="id_file">
                  Cookies
                </FormLabel>
                <FormControl>
                  <Input
                    id="id_file"
                    className="w-60"
                    type="file"
                    onChange={(e) => field.onChange(e.target.files?.[0])}
                  />
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />
        </form>
      </Form>
    );
  },
);

CookiesForm.displayName = "CookiesForm";
export { CookiesForm };
